package com.education.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.education.platform.common.ResultCode;
import com.education.platform.entity.SystemConfig;
import com.education.platform.exception.BusinessException;
import com.education.platform.mapper.SystemConfigMapper;
import com.education.platform.service.SystemConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 系统配置服务实现类
 *
 * @author education-platform
 * @since 2024-09-27
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SystemConfigServiceImpl implements SystemConfigService {

    private final SystemConfigMapper systemConfigMapper;

    @Override
    @Transactional
    @CacheEvict(value = "systemConfig", allEntries = true)
    public Long createConfig(SystemConfig systemConfig) {
        // 检查配置键是否已存在
        SystemConfig existing = systemConfigMapper.selectByConfigKey(systemConfig.getConfigKey());
        if (existing != null) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR);
        }
        
        if (systemConfig.getIsPublic() == null) {
            systemConfig.setIsPublic(false);
        }
        
        systemConfigMapper.insert(systemConfig);
        log.info("创建系统配置成功, KEY: {}", systemConfig.getConfigKey());
        return systemConfig.getId();
    }

    @Override
    @Transactional
    @CacheEvict(value = "systemConfig", allEntries = true)
    public void updateConfig(Long id, SystemConfig systemConfig) {
        SystemConfig config = getConfigById(id);
        
        config.setConfigValue(systemConfig.getConfigValue());
        config.setConfigType(systemConfig.getConfigType());
        config.setDescription(systemConfig.getDescription());
        config.setIsPublic(systemConfig.getIsPublic());
        
        systemConfigMapper.updateById(config);
        log.info("更新系统配置成功, ID: {}", id);
    }

    @Override
    @Transactional
    @CacheEvict(value = "systemConfig", allEntries = true)
    public void deleteConfig(Long id) {
        systemConfigMapper.deleteById(id);
        log.info("删除系统配置成功, ID: {}", id);
    }

    @Override
    public SystemConfig getConfigById(Long id) {
        SystemConfig config = systemConfigMapper.selectById(id);
        if (config == null) {
            throw new BusinessException(ResultCode.NOT_FOUND);
        }
        return config;
    }

    @Override
    @Cacheable(value = "systemConfig", key = "#configKey")
    public SystemConfig getConfigByKey(String configKey) {
        return systemConfigMapper.selectByConfigKey(configKey);
    }

    @Override
    @Cacheable(value = "systemConfig", key = "'value:' + #configKey")
    public String getConfigValue(String configKey) {
        SystemConfig config = getConfigByKey(configKey);
        return config != null ? config.getConfigValue() : null;
    }

    @Override
    public String getConfigValue(String configKey, String defaultValue) {
        String value = getConfigValue(configKey);
        return value != null ? value : defaultValue;
    }

    @Override
    @Transactional
    @CacheEvict(value = "systemConfig", allEntries = true)
    public void setConfigValue(String configKey, String configValue) {
        SystemConfig config = getConfigByKey(configKey);
        if (config == null) {
            // 不存在则创建
            config = new SystemConfig();
            config.setConfigKey(configKey);
            config.setConfigValue(configValue);
            config.setConfigType(SystemConfig.ConfigType.STRING.name());
            config.setIsPublic(false);
            systemConfigMapper.insert(config);
            log.info("创建系统配置, KEY: {}", configKey);
        } else {
            // 存在则更新
            config.setConfigValue(configValue);
            systemConfigMapper.updateById(config);
            log.info("更新系统配置, KEY: {}", configKey);
        }
    }

    @Override
    public List<SystemConfig> getAllConfigs() {
        return systemConfigMapper.selectList(new LambdaQueryWrapper<SystemConfig>()
                .orderByAsc(SystemConfig::getConfigKey));
    }

    @Override
    @Cacheable(value = "systemConfig", key = "'public:all'")
    public List<SystemConfig> getPublicConfigs() {
        return systemConfigMapper.selectPublicConfigs();
    }

    @Override
    @Cacheable(value = "systemConfig", key = "'public:map'")
    public Map<String, String> getPublicConfigMap() {
        List<SystemConfig> configs = getPublicConfigs();
        return configs.stream()
                .collect(Collectors.toMap(
                        SystemConfig::getConfigKey,
                        config -> config.getConfigValue() != null ? config.getConfigValue() : "",
                        (v1, v2) -> v1
                ));
    }

    @Override
    public List<SystemConfig> getConfigsByType(String configType) {
        return systemConfigMapper.selectByConfigType(configType);
    }

    @Override
    @Transactional
    @CacheEvict(value = "systemConfig", allEntries = true)
    public void batchUpdateConfigs(Map<String, String> configMap) {
        for (Map.Entry<String, String> entry : configMap.entrySet()) {
            setConfigValue(entry.getKey(), entry.getValue());
        }
        log.info("批量更新系统配置成功, 数量: {}", configMap.size());
    }
}

